package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.hjq.base.BaseAdapter;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.event.DeviceItemChangeEvent;
import com.qiantu.phone.event.DeviceListChangeEvent;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.ui.activity.AddDevice1Activity;
import com.qiantu.phone.ui.activity.ControllerDeviceAcitvity;
import com.qiantu.phone.ui.activity.ControllerOrderActivity;
import com.qiantu.phone.ui.activity.ControllerSettingActivity;
import com.qiantu.phone.ui.activity.DeviceSettingActivity;
import com.qiantu.phone.ui.adapter.SmartControllerAdapter;
import com.qiantu.phone.ui.adapter.SmartControllerCategoryAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.StatusLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * time   : 2021/12/22
 * 智控系统
 */
public final class SmartControlFragment extends TitleBarFragment<AppActivity>
        implements OnRefreshLoadMoreListener, StatusAction {

    public static SmartControlFragment newInstance() {
        SmartControlFragment fragment = new SmartControlFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    private StatusLayout mStatusLayout;
    private ViewPager2 controllerViewPager;
    private RecyclerView categoryRecyclerView;
    private SmartControllerAdapter mSmartControlAdapter;
    private SmartControllerCategoryAdapter mSmartControllerCategoryAdapter;
    private int lastPositionOffsetPixels;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_smart_control;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mStatusLayout = findViewById(R.id.status_layout);
        controllerViewPager = findViewById(R.id.controller_view_pager);
        categoryRecyclerView = findViewById(R.id.category_recycler_view);
        mSmartControlAdapter = new SmartControllerAdapter(getContext());
        controllerViewPager.setAdapter(mSmartControlAdapter);
        controllerViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.i("luzx", "onPageScrolled:position:" + position + " positionOffset:" + positionOffset + " positionOffsetPixels:" + positionOffsetPixels);
                int totalCount = mSmartControlAdapter.getItemCount();
                Log.i("luzx", "totalCount:" + totalCount);
                if (totalCount > 1) {
                    boolean toRight = false;
                    boolean toLeft = false;
                    int width = controllerViewPager.getWidth() - getResources().getDimensionPixelSize(R.dimen.dp_128);
                    if (lastPositionOffsetPixels == 0 && positionOffsetPixels > 0) {
                        if (positionOffsetPixels < width / 2f) {
                            toRight = true;
                        } else if (positionOffsetPixels > width / 2f) {
                            toLeft = true;
                        }
                    } else {
                        if (lastPositionOffsetPixels < positionOffsetPixels) {
                            toRight = true;
                        } else if (lastPositionOffsetPixels > positionOffsetPixels) {
                            toLeft = true;
                        }
                    }
                    lastPositionOffsetPixels = positionOffsetPixels;
                    //正在向右滑到最后一个
                    if (toRight && position == totalCount - 2) {
                        setRecyclerViewPadding(getResources().getDimensionPixelSize(R.dimen.dp_90), 0);
                    } else if (toLeft && position == 0) { //正在向左滑到第一个
                        setRecyclerViewPadding(0, getResources().getDimensionPixelSize(R.dimen.dp_90));
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }

            @Override
            public void onPageSelected(int position) {
                Log.i("luzx", "onPageSelected:" + position);
                initSlaveData();
                mSmartControlAdapter.select(position);
                if (mSmartControlAdapter.getData() != null && mSmartControlAdapter.getData().size() == 1) {
                    setRecyclerViewPadding(0, 0);
                } else {
                    if (position == mSmartControlAdapter.getItemCount() - 1) {//最后一个
                        setRecyclerViewPadding(getResources().getDimensionPixelSize(R.dimen.dp_90), 0);
                    } else if (position == 0) { //第一个
                        setRecyclerViewPadding(0, getResources().getDimensionPixelSize(R.dimen.dp_90));
                    }
                }
            }
        });
        mSmartControlAdapter.setOnChildClickListener(R.id.btn_setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                ControllerBean controller = mSmartControlAdapter.getData().get(position);
//                ControllerSettingActivity.start(getContext(), controller.getControllerSerialNo());
                ControllerDeviceAcitvity.start(getContext(), controller.getControllerSerialNo());
            }
        });
        mSmartControlAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                controllerViewPager.setCurrentItem(position);
            }
        });
        categoryRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mSmartControllerCategoryAdapter = new SmartControllerCategoryAdapter(getContext());
        categoryRecyclerView.setAdapter(mSmartControllerCategoryAdapter);
        mSmartControllerCategoryAdapter.setOnChildClickListener(R.id.controller_sort, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                Map<String, SparseArray<List<ControllerBean>>> item = mSmartControllerCategoryAdapter.getData().get(position);
                SparseArray<List<ControllerBean>> sparseArray = null;
                for(String key : item.keySet()){
                    sparseArray = item.get(key);
                }
                List<ControllerBean> normal = null;
                if(sparseArray != null){
                    normal = sparseArray.get(0);
                }
                ControllerOrderActivity.start(getContext(), "",normal);
            }
        });
        showLoading();
    }

    private void setRecyclerViewPadding(int leftItemPadding, int rightItemPadding) {
        RecyclerView recyclerView = (RecyclerView) controllerViewPager.getChildAt(0);
        recyclerView.setPadding(leftItemPadding, 0, rightItemPadding, 0);
        if (leftItemPadding > 0 || rightItemPadding > 0) {
            recyclerView.setClipToPadding(false);
        } else {
            recyclerView.setClipToPadding(true);
        }
    }

    @Override
    protected void initData() {
        Observable.create(new ObservableOnSubscribe<List<ControllerBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ControllerBean>> emitter) throws Exception {
                List<ControllerBean> data = LLControllerDBManager.getInstance(getContext()).getHostControllers();
                emitter.onNext(data);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<ControllerBean>>() {
                    @Override
                    public void accept(List<ControllerBean> data) throws Exception {
                        if(data == null || data.size() == 0){
                            showEmpty();
                        }else{
                            showComplete();
                        }
                        mSmartControlAdapter.setData(data);
                        if (data != null && data.size() == 1) {
                            setRecyclerViewPadding(0, 0);
                        } else {
                            if (controllerViewPager.getCurrentItem() == mSmartControlAdapter.getItemCount() - 1) {
                                setRecyclerViewPadding(getResources().getDimensionPixelSize(R.dimen.dp_90), 0);
                            } else if (controllerViewPager.getCurrentItem() == 0) {
                                setRecyclerViewPadding(0, getResources().getDimensionPixelSize(R.dimen.dp_90));
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(R.string.load_area_data_failed);
                    }
                });
    }

    private void showEmpty(){
        showEmpty(R.attr.img_emptystate_nodevice, R.string.no_device, R.string.add, new StatusLayout.OnBtnClickListener() {
            @Override
            public void onClick(StatusLayout layout) {
                Intent intent = new Intent(getContext(), AddDevice1Activity.class);
                startActivity(intent);
            }
        });
    }

    private void initSlaveData() {
        Log.i("luzx", "getCurrentItem:" + controllerViewPager.getCurrentItem());
        if(mSmartControlAdapter.getData() == null || mSmartControlAdapter.getData().size() == 0){
            return;
        }
        ControllerBean host = mSmartControlAdapter.getData().get(controllerViewPager.getCurrentItem());
        if (host == null || TextUtils.isEmpty(host.getControllerSerialNo())) {
            return;
        }
        List<ControllerBean> data = LLControllerDBManager.getInstance(getContext()).getSlaveControllers(host.getControllerSerialNo());
        //分类列表
        List<Map<String, SparseArray<List<ControllerBean>>>> categoryList = new ArrayList<>();
        for(int i=0; i<LLDeviceUtil.controllerCategoryArray.length; i++){
            Map<String, SparseArray<List<ControllerBean>>> map = new HashMap<>();
            map.put(LLDeviceUtil.controllerCategoryArray[i], null);
            categoryList.add(map);
        }
        for (ControllerBean slave : data) {
            String typeName = LLDeviceUtil.getControllerTypeName(slave.getProductModel());
            Map<String, SparseArray<List<ControllerBean>>> map = null;
            SparseArray<List<ControllerBean>> sparseArray = null;

            if (typeName.equals(getString(R.string.area_gateway))){//区域主机 x个从机
                List<ControllerBean> slaveData = LLControllerDBManager.getInstance(getContext()).getSlaveControllers(slave.getControllerSerialNo());
                slave.setSlaveArr(slaveData);
            }

            for (Map<String, SparseArray<List<ControllerBean>>> category : categoryList) {
                if(category.keySet().contains(typeName)){
                    map = category;
                    sparseArray = category.get(typeName);
                    break;
                }
            }
            if (sparseArray == null) {
                sparseArray = new SparseArray<>();
                sparseArray.put(0, new ArrayList<>());//正常智控器
                sparseArray.put(1, new ArrayList<>());//已停用智控器
                map.put(typeName, sparseArray);
            }
            if (slave.isIsDisable()) {
                sparseArray.get(1).add(slave);
            } else {
                sparseArray.get(0).add(slave);
            }
        }

        Iterator<Map<String, SparseArray<List<ControllerBean>>>> iterator = categoryList.iterator();
        while (iterator.hasNext()) {
            Map<String, SparseArray<List<ControllerBean>>> map = iterator.next();
            for (String key : map.keySet()) {
                if(map.get(key) == null){
                    iterator.remove();
                }
            }
        }
        Log.i("luzx", "categoryList size:" + categoryList.size());
        mSmartControllerCategoryAdapter.setData(categoryList);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshControllerEvent(RefreshControllerEvent event) {
        initData();
        //重新设置，删除控制器后
        controllerViewPager.setCurrentItem(controllerViewPager.getCurrentItem(), false);
        initSlaveData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceChangeEvent(DeviceItemChangeEvent event) {
        DeviceBean device = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(event.deviceSerialNo);
        if(device != null){
            if(device.getType().equals("wall_switch") && device.getStateData().getStatus().getKey_operate() == 20){
                DeviceSettingActivity.start(getContext(), device.getDeviceSerialNo(), false);
            }
        }
    }
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//        postDelayed(() -> {
//            mAdapter.clearData();
////            mAdapter.setData(analogData());
//            mRefreshLayout.finishRefresh();
//        }, 1000);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//        postDelayed(() -> {
//            mAdapter.addData(analogData());
//            mRefreshLayout.finishLoadMore();
//
//            mAdapter.setLastPage(mAdapter.getCount() >= 100);
//            mRefreshLayout.setNoMoreData(mAdapter.isLastPage());
//        }, 1000);
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}